package br.com.android.financas.activities;

import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import br.com.android.financas.R;
import br.com.android.financas.adapter.CategoriaSpinnerAdapter;
import br.com.android.financas.adapter.DataAdapter;
import br.com.android.financas.helper.HomeHelper;
import br.com.android.financas.model.Categoria;
import br.com.android.financas.model.Despesa;
import br.com.android.financas.model.Frequencia;
import br.com.android.financas.model.Recorrente;
import br.com.android.financas.repositorio.RepositorioCategoria;
import br.com.android.financas.repositorio.RepositorioDespesa;
import br.com.android.financas.repositorio.impl.RepositorioCategoriaImpl;
import br.com.android.financas.repositorio.impl.RepositorioDespesaImpl;
import br.com.android.financas.watcher.CurrencyWatcher;


public class HomeRecorrente extends HomeHelper<Recorrente> {

	private static final String CLICK_RECORRENTE_ID = "id";
	private EditText campoValor,campoDescricao;
	private Spinner campoCategoria,campoData,campoFrequencia;
	private RepositorioCategoria repositorioCategoria;
	private RepositorioDespesa repositorioDespesa;
	private Activity activity;
	private boolean update=false;

	public HomeRecorrente() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recorrente_screen);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		try {
			repositorioCategoria = new RepositorioCategoriaImpl(this);
			repositorioDespesa=new RepositorioDespesaImpl(this);

			Intent intent = getIntent();
			campoData = (Spinner) findViewById(R.recorrente.data);
			campoValor = (EditText) findViewById(R.recorrente.valor);
			campoDescricao = (EditText) findViewById(R.recorrente.descricao);
			campoCategoria = (Spinner) findViewById(R.recorrente.categoria);
			//campoFrequencia = (Spinner) findViewById(R.recorrente.frequencia);


			// ArrayAdapter<Cores> adapter = new ArrayAdapter<Cores>(this,
			// android.R.layout.simple_spinner_item, Cores.values());
			ArrayAdapter<Categoria> adapter = new CategoriaSpinnerAdapter(this,
					R.layout.categoria_item, repositorioCategoria.listar(),
					"Selecione");
			campoCategoria.setAdapter(adapter);
			String data=(new DateTime()).toString("dd");
			getInstance().setData(new Date());

			ArrayAdapter<Frequencia> frequenciaAdapter=new ArrayAdapter<Frequencia>(this, android.R.layout.simple_spinner_item, Frequencia.values());

			//campoFrequencia.setAdapter(frequenciaAdapter);
			//campoFrequencia.setSelection(frequenciaAdapter.getPosition(Frequencia.MENSAL));

			getInstance().setFrequencia(Frequencia.MENSAL);

			if (intent.getExtras() != null
					&& intent.getExtras().get(CLICK_RECORRENTE_ID) != null) {
				// get
				Integer id = (Integer) intent.getExtras().get(CLICK_RECORRENTE_ID);
				setId(id);

				campoValor.setText(NumberFormat.getCurrencyInstance().format(getInstance().getValor()));
				data= (new DateTime(getInstance().getData().getTime())).toString("dd");
				campoCategoria.setSelection(adapter.getPosition(getInstance().getCategoria()));
				campoDescricao.setText(getInstance().getDescricao());
				//campoFrequencia.setSelection(frequenciaAdapter.getPosition(getInstance().getFrequencia()));

			}

			List<String> datas=new ArrayList<String>();

			datas.add(data);

			DataAdapter dataAdapter= new DataAdapter(this, android.R.layout.simple_spinner_item, datas);
			dataAdapter.setDataSelecionada(new DateTime(getInstance().getData().getTime()));
			dataAdapter.setSoDia(true);
			campoData.setAdapter(dataAdapter);

			campoValor.setRawInputType(Configuration.KEYBOARD_12KEY);

			campoValor.addTextChangedListener(new CurrencyWatcher(campoValor));

			activity=this;



		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.home_despesa, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getIntent().putExtra("changed", false);
			setResult(RESULT_CANCELED, getIntent());
			finish();
			return true;
		case R.id.menu_save:

			if(!isValid()){
				Toast.makeText(this, R.string.required_fields, Toast.LENGTH_LONG).show();
				return false;
			}

			adicionarMeses();

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}


	private void adicionarMeses(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		LayoutInflater factory = LayoutInflater.from(this);
	    View layout = factory.inflate(R.layout.apagar_despesa, null);
		final CheckBox todas = (CheckBox) layout.findViewById(R.apagar.todasGrupo);
		final CheckBox frente = (CheckBox) layout.findViewById(R.apagar.paraFrente);

		todas.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean check) {
				if(check){
					frente.setVisibility(View.INVISIBLE);
				}else
					frente.setVisibility(View.VISIBLE);
			}
		});

		builder.setView(layout);
		builder.setTitle(R.string.atualizar_movimentacoes);

		frente.setText(R.string.apartir_deste);
		todas.setText(R.string.todos_meses);

		builder.setCancelable(false);
		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {
					@SuppressWarnings("deprecation")
					public void onClick(DialogInterface dialog, int id) {
						try {

							if(!todas.isChecked() && !frente.isChecked()){
								Toast.makeText(activity,R.string.escolha, Toast.LENGTH_LONG).show();

							}else{

								if (getInstance().getId() == null) {
									if(!save())
										throw new SQLException("Erro ao salvar");
								} else {
									update=true;
									update();
								}

								List<DateTime> meses=new ArrayList<DateTime>();
								if(todas.isChecked())
									meses=repositorioDespesa.getMeses();
								else if(frente.isChecked())
									meses=repositorioDespesa.getMeses(new Date());

								if(meses.size()>0){
									Categoria categoria=getInstance().getCategoria();
									String descricao=getInstance().getDescricao();
									double valor=getInstance().getValor();

									if(!update){
										Despesa pai=new Despesa();
										pai.setCategoria(categoria);
										pai.setDescricao(descricao);
										pai.setValor(valor);
										pai.setData(meses.get(0).withTimeAtStartOfDay().toDate());
										pai.setRecorrente(getInstance());
										repositorioDespesa.inserir(pai);
										meses.remove(0);

										for(DateTime mes: meses){

											MutableDateTime m=new MutableDateTime(mes);

											m.setDayOfMonth(getInstance().getData().getDate());

											Despesa despesa=new Despesa();

											despesa.setCategoria(categoria);
											despesa.setDescricao(descricao);
											despesa.setValor(valor);
											despesa.setData(m.toDateTime().withTimeAtStartOfDay().toDate() );
											despesa.setPai(pai);
											despesa.setRecorrente(getInstance());

											repositorioDespesa.inserir(despesa);
										}
									}else{
										List<Despesa> despesas=new ArrayList<Despesa>();

										if(todas.isChecked())
											despesas=repositorioDespesa.getRecorrentes(getInstance());
										else if(frente.isChecked())
											despesas=repositorioDespesa.getRecorrentes(getInstance(), new Date());


										for(Despesa despesa:despesas){

											MutableDateTime m=new MutableDateTime(despesa.getData().getTime());

											m.setDayOfMonth(getInstance().getData().getDate());


											despesa.setCategoria(categoria);
											despesa.setDescricao(descricao);
											despesa.setValor(valor);
											despesa.setData(m.toDateTime().withTimeAtStartOfDay().toDate());

											repositorioDespesa.atualizar(despesa);

										}
									}
								}

								Toast.makeText(activity,R.string.atualizado_sucesso, Toast.LENGTH_LONG).show();
								getIntent().putExtra("changed", true);
								setResult(RESULT_OK, getIntent());
								finish();
							}
						} catch (SQLException e) {
						}

					}
				});
		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();


	}

	public static void callMe(Activity c, Integer id) {
		//Intent intent = new Intent(c, HomeDespesa.class);
		//intent.putExtra(CLICK_DESPESA_ID, id);
		c.getIntent().setClass(c, HomeRecorrente.class);
		c.getIntent().putExtra(CLICK_RECORRENTE_ID, id);
		c.startActivityForResult(c.getIntent(), 1);
	}

}
